<template>
  <div class="preview" @wheel.prevent="onWheel">
    <div class="dispatch">
      <div class="flex justify-between">
        <span>{{ t["预览"] }}</span>
        <div class="flex">
          <a-select
            allowClear
            v-model="stationId"
            :options="stationList"
            style="width: 160px"
            :placeholder="t['请选择基站']"
          ></a-select>
          <a-button :loading="loading" type="primary" @click="save">
            {{ t["下发"] }}
          </a-button>
        </div>
      </div>
    </div>
    <div class="image-container">
      <img :src="dispatchParams.image" :style="{ transform: `scale(${scale})` }" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { preview, saveAndSend } from "@/api/service/priceTag/priceTag";

import { boundMedia } from "@/api/service/lcd-device/lcd-device";
import { list } from "../lcd-device/data/curd";
import { form, stationList } from "../priceTag/data/form";
import { deviceMode, dispatchParams, showDispatch } from "./form";

const loading = ref(false);
const t = translate("公共模块");
const stationId = ref("");

const scale = ref(1);

const onWheel = (e: WheelEvent) => {
  if (e.deltaY > 0) {
    scale.value += 0.2;
  } else if (scale.value > 0.4) {
    scale.value -= 0.2;
  }
};

const save = async () => {
  loading.value = true;
  const { tagId, templateId, goodsId, goodsList } = form.value;

  try {
    if (deviceMode.value === "ink") {
      await saveAndSend({
        tagId,
        templateId,
        goodsId,
        stationId: stationId.value,
        goodsList: dispatchParams.value.goodsList
      });
    } else {
      await boundMedia({
        templateId,
        mediaId: tagId,
        goodsList: dispatchParams.value.goodsList
      });
      list();
    }
  } catch (error) {
    loading.value = false;
  }
  loading.value = false;
  showDispatch.value = false;
};
const previewImage = async () => {
  const { data } = await preview({
    goodsList: dispatchParams.value.goodsList,
    templateId: form.value.templateId,
    tagCode: form.value.tagCode
  });
  dispatchParams.value.image = data;
};
watch(
  [() => dispatchParams.value.templateId, () => dispatchParams.value.selectedGoods],
  () => {
    if (dispatchParams.value.templateId && dispatchParams.value.selectedGoods.length > 0) {
      previewImage();
    }
  },
  {
    deep: true,
    immediate: true
  }
);
</script>

<style lang="scss" scoped>
.preview {
  @apply flex-1 flex flex-col;
  min-width: 400px;
  background-color: #eee;
  position: relative;
  overflow: hidden;
  height: calc(100vh - 74px);

  .dispatch {
    @apply p-2 bg-gray-50;
  }

  .image-container {
    @apply flex-1 flex justify-center items-center;
    overflow: hidden;
    width: 100%;

    img {
      max-width: 100%;
    }
  }
}
</style>
